/**
 * Author(s): xuming.Wong <xuming.Wong@gmail.com>
 */
#include "TerrainCreateDialog.h"

#include "GameBuilder.h"

namespace PQBuilder
{
	TerrainCreateDialog::TerrainCreateDialog(QWidget *parent)
		: QDialog(parent),_ui(new Ui::TerrainCreateDialogUI)
	{
		_ui->setupUi(this);
		
		loadDiffuseTexIcons();
	}

	void TerrainCreateDialog::loadDiffuseTexIcons()
	{
		_ui->diffuseTexListWidget->clear();

		int cnt=SEngine.getNumTerrainTexture();
		for(int i=0;i<cnt;i++){
			PQEngine::GPKFile* file=SEngine.getTerrainTextureFile(i);
			if(!file||!file->ok()){
				return;
			}

			file->open();
			int len=file->length();
			char* buf=new char[len];
			file->read(buf,len);
			file->close();


			QByteArray bytes(buf,len);
			QImage image;
			image.loadFromData(bytes);
			QPixmap pixmap=QPixmap::fromImage(image);
			QString name=QString::fromStdString(file->getFileName());
			QListWidgetItem *item=new QListWidgetItem(QIcon(pixmap),name);
			item->setWhatsThis(name);
			item->setToolTip(name);

			_ui->diffuseTexListWidget->addItem(item);
			
			delete buf;
		}
	}


	TerrainCreateDialog::~TerrainCreateDialog()
	{
		delete _ui;
	}

	void TerrainCreateDialog::accept()
	{
		
		int x=_ui->spinBoxSlotX->value();
		int y=_ui->spinBoxSlotY->value();

		int row=_ui->diffuseTexListWidget->currentRow();
		SGameBuilder.createFlatTerrain(x,y,row);
		QDialog::accept();
	}

	void TerrainCreateDialog::reject()
	{
		QDialog::reject();
	}

}
